#!/bin/bash
:<<!
检查当前分支是否可以打包及可打包情况下输出所打包的所有分支信息(判断方法如下：)
!
#responseResult=$(git log --graph --pretty=format:'%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges )
#responseResult=$(git log --pretty=format:'%s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges)

#responseResult=$(git log --pretty=format:'%C(yellow)%H' --after "10-12-2022" --no-merges )

#git log --pretty=format:'-%C(yellow)%d%Creset %s' --after "2022-10-16"

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
# CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}
#echo "CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute}"

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
rebasebranch_last_commit_date_script_path="$(sh ${qscript_path_get_filepath} qbase rebasebranch_last_commit_date)"
first_commit_info_after_date_script_path="$(sh ${qscript_path_get_filepath} qbase first_commit_info_after_date)"



# shell 参数具名化
show_usage="args: [-date , -use]\
                                  [--searchFromDateString=, --useBySource=]"
                                  
while [ -n "$1" ]
do
        case "$1" in
                -date|--searchFromDateString) searchFromDateString=$2; shift 2;;
                -curBranch|--currentBranch) currentBranch=$2; shift 2;;
                --) break ;;
                *) break ;;
        esac
done


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}

# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'


function debug_log() {
    # 只有直接执行本脚本的时候才能够输出日志，不然如果是形如 echo $(sh xx.sh) 的时候会导致结果值不对
    if [ "${is_Directly_execute_this_script}" == true ]; then
        echo "$1"
    fi
}

#echo "searchFromDateString=${searchFromDateString}"


function getSourceBranchContainBranchs() {
    branchArrayForFisrtCommit=$1
    sourceBranchCannotBeArray=$2  # 当第一次提交在多个分支上都contain包含的时候，为了获取是哪个分支，添加的"不能够是哪些分支"的参数
    sourceBranchCannotBeArray=(${sourceBranchCannotBeArray})
    branchCountForFisrtCommit=${#branchArrayForFisrtCommit[@]}
    
    
    debug_log "\n------下面开始获取firstCommitId:${firstCommitId}的提交所属的根源远程功能分支名------"
    #sourceBranchResultInContainBranchs=${branchArrayForFisrtCommit[${branchCountForFisrtCommit}-1]} # 错误方法，最后一个不一定是
    for ((i=branchCountForFisrtCommit-1;i>=0;i--))
    {
        branchName=${branchArrayForFisrtCommit[i]}
        if [[ "${sourceBranchCannotBeArray[*]}" =~ ${branchName} ]]; then
            debug_log "${i}:${branchName} pass"
            continue
        else
            debug_log "${i}:${branchName} break"
            sourceBranchResultInContainBranchs=${branchName}
            break
        fi
    }
    
    if [ -z "${sourceBranchResultInContainBranchs}" ]; then
        echo "❌错误：未找到本分支${currentBranch}在${searchFromDateString}后第一条提交记录《${firstCommitId}:${firstCommitDes}》的根源分支名"
        return 1
    fi

    debug_log "sourceBranchResultInContainBranchs=${sourceBranchResultInContainBranchs}"

    sourceBranchResultInContainBranchs=${sourceBranchResultInContainBranchs##*/} # 取最后的component
    debug_log "sourceBranchResultInContainBranchs=${sourceBranchResultInContainBranchs}"
}


debug_log "正在执行命令(获取指定分支在指定日期后的第一条提交记录及其所属的所有分支):《 ${PURPLE}sh ${first_commit_info_after_date_script_path} -date \"${searchFromDateString}\" -curBranch \"${currentBranch}\" ${NC}》${NC}"
sourceBranchJson=$(sh ${first_commit_info_after_date_script_path} -date "${searchFromDateString}" -curBranch "${currentBranch}")
if [ $? != 0 ]; then
    printf "❌Errror:出错了，出错发生在执行如下命令的时候:《 ${PURPLE}sh ${first_commit_info_after_date_script_path} -date \"${searchFromDateString}\" -curBranch \"${currentBranch}\" ${NC}》，${NC}"
    echo "该该命令出错的原因如下: ${RED}${sourceBranchJson}${NC}"  # 此时值为出错原因
    exit 1
fi
# debug_log "✅>>>>>>>> sourceBranchJson=${sourceBranchJson} <<<<<<<✅"
firstCommitId=$(echo "$sourceBranchJson" | jq -r ".firstCommitId")
if [ $? != 0 ]; then
    echo "${RED}❌Error:发生错误了,从 ${BLUE}$sourceBranchJson ${RED}中获取 ${BLUE}.firstCommitId ${RED}的值失败，请检查其是否未正确转义${NC}"
    exit 1
fi
firstCommitDes=$(echo "$sourceBranchJson" | jq -r '.firstCommitDes')
if [ $? != 0 ]; then
    echo "${RED}❌Error:发生错误了,从 ${BLUE}$sourceBranchJson ${RED}中获取 ${BLUE}.firstCommitDes ${RED}的值失败，请检查其是否未正确转义${NC}"
    exit 1
fi
sourceBranchNames=$(echo "$sourceBranchJson" | jq -r '.sourceBranchNames')
if [ $? != 0 ]; then
    echo "${RED}❌Error:发生错误了,从 ${BLUE}$sourceBranchJson ${RED}中获取 ${BLUE}.sourceBranchNames ${RED}的值失败，请检查其是否未正确转义${NC}"
    exit 1
fi
debug_log "✅>>>>>>>> firstCommitId=${firstCommitId} <<<<<<<✅"
debug_log "✅>>>>>>>> firstCommitDes=${firstCommitDes} <<<<<<<✅"
debug_log "✅>>>>>>>> sourceBranchNames=${sourceBranchNames} <<<<<<<✅"
debug_log "${GREEN}============ 恭喜:获得 ${BLUE}${currentBranch} ${GREEN}分支在指定日期${BLUE}${searchFromDateString}${GREEN}后的第一条提交记录【 ${BLUE}${firstCommitId}${GREEN}: ${BLUE}${firstCommitDes}${GREEN} 】的所属所有分支名sourceBranchsNameForFisrtCommit=${BLUE}${sourceBranchNames}"


sourceBranchCannotBeArray=("origin/development" "origin/dev_publish_out" "origin/dev_publish_in" "origin/dev_all")
getSourceBranchContainBranchs "${sourceBranchNames[*]}" "${sourceBranchCannotBeArray[*]}"
if [ $? != 0 ]; then
    exit 1
fi
debug_log "${GREEN}============ 恭喜:获得 ${BLUE}${currentBranch} ${GREEN}分支在指定日期${BLUE}${searchFromDateString}${GREEN}后的第一条提交记录【 ${BLUE}${firstCommitId}${GREEN}: ${BLUE}${firstCommitDes}${GREEN} 】的根源分支名sourceBranchNameForFisrtCommit=${BLUE}${sourceBranchResultInContainBranchs}"

echo "${sourceBranchResultInContainBranchs}"